package cn.yunhe.action;

import com.opensymphony.xwork2.ActionSupport;
import lombok.Getter;
import lombok.Setter;
import org.apache.struts2.ServletActionContext;

import java.io.*;

public class UploadAction extends ActionSupport {
    @Getter
    @Setter
    private String title;

    @Getter
    @Setter
    private File upload;

    @Getter
    @Setter
    private String uploadContentType;
    @Getter
    @Setter
    private String uploadFileName;


    private String savePath;
    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    public String getSavePath() {

        return ServletActionContext.getServletContext().getRealPath(savePath);
    }


    private void doUpload(File file, String uploadFilePath) {
        try {
            FileOutputStream fos = new FileOutputStream(uploadFilePath);
            FileInputStream fis = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len=0 ;
            while ((len = fis.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }
            fis.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public String execute() throws Exception {
        String uploadPath=getSavePath()+"\\"+getUploadFileName();
        doUpload(upload,uploadPath);
        return SUCCESS;
    }
}
